<template>
  <b-page class="khgl-page" :load="!loading">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="客户昵称">
              <a-input v-model="queryParam.nickname" placeholder="" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="所属成员">
              <a-select
                placeholder="所属成员"
                :value="queryParam.staffUserId"
                style="height: 32px"
                allowClear
                @change="memberChange">
                <a-select-option
                  v-for="item in memberList"
                  :key="item.userId"
                >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="企业标签">
              <a-input v-model="queryParam.showTag" placeholder="" allowClear @click="searchTag=true"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="添加时间">
              <a-range-picker @change="timeChange" allowClear valueFormat="YYYY-MM-DD hh:mm:ss"/>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item label="添加渠道">
              <a-select
                placeholder="渠道"
                :value="queryParam.sourceName"
                style="height: 32px"
                allowClear
                @change="channelChange">
                <a-select-option
                  v-for="item in sourceList"
                  :key="item.value"
                >{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="性别">
              <a-select
                placeholder="性别"
                :value="queryParam.gender"
                style="height: 32px"
                allowClear
                @change="genderChange">
                <a-select-option
                  v-for="item in genderList"
                  :key="item.value"
                >{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="流失状态">
              <a-select
                placeholder="流失状态"
                :value="queryParam.leaveStatus"
                style="height: 32px"
                allowClear
                @change="lossChange">
                <a-select-option
                  v-for="item in lossList"
                  :key="item.value"
                >{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6 " :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="getData">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetQueryParam">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="d-jcs-aic" style="margin-bottom: 25px">
      <div class="select-state d-aic">共<span class="select-state-num">{{ parameter.totalCount }}</span>个客户 已选择<span
        class="select-state-num">{{ selectedRowKeys.length }}</span>个客户
        <div class="material-icons select-state-icon" :class="{'active':exportLoading}">autorenew</div>
        <a-button type="link" style="padding: 0;color: #ff5f5f" @click="updateKhgl">更新数据</a-button>
      </div>
      <div>
        <b-button style="margin-right: 15px" btn-content="批量打标签" @click="batchTag"/>
        <a :href="url">
          <b-button btn-content="导出Excel"/>
        </a>
      </div>
    </div>
    <a-table
      rowKey="externalUserId"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :columns="columns"
      :data-source="dataList"
      @change="handleTableChange"
    >
      <span slot="nickname" slot-scope="text, record">
        <div class="d-aic">
          <div>
            <img class="user-avatar" :src="record.headImgUrl">
          </div>
          <div class="ml-10">
            <div class="remark-name">{{ record.remarkName }}</div>
            <div class="nickname-diy">昵称：{{ record.nickname }}</div>
          </div>
        </div>
      </span>
      <span slot="gender" slot-scope="text, record">
        {{ !record.gender?'未知':record.gender===1?'男':'女' }}
      </span>
      <span slot="tag" slot-scope="text, record" class="d-aic">
        <span class="tag-item-style d-jcc-aic" v-for="(item,index) in record.tagList" :key="index">{{ item }}</span>
      </span>
      <span slot="addTIme" slot-scope="text, record">
        {{ getTime(record.addTIme) }}
      </span>
      <template slot="leaveStatusTitle">
        <span>流失率</span>
        <a-tooltip placement="top">
          <template slot="title">
            <div>被动删除：客户删除成员</div>
            <div>主动删除：成员删除客户</div>
          </template>
          <a-icon style="margin-left: 10px" type="exclamation-circle"/>
        </a-tooltip>
      </template>
      <span slot="leaveStatus" slot-scope="text, record">
        {{ !record.leaveStatus?'未流失':record.leaveStatus===1?'被动删除':'主动删除' }}
      </span>
      <span slot="externalUserId" slot-scope="text, record">
        <a-button type="link" @click="gotoDetail(record.id)">详情</a-button>
      </span>
    </a-table>
    <a-modal v-model="updateTag" :title="null" :footer="null" width="640px">
      <div class="modal-class-title">
        批量打标签
      </div>
      <div class="tag-update-wrap">
        <div class="d-aic">
          <b-data-title title="已选中："/>
          <span v-for="item in selectedRows" :key="item.id">{{ item.remarkName }}，</span>
          {{ selectedRowKeys.length }}个客户,请选择标签
        </div>
        <div class="mt-30">
          <b-data-title title="标签组："/>
          <div class="d-aic tag-group-content mt-10" v-for="item in TagGroupList" :key="item.groupId">
            <div class="tag-group-name">{{ item.groupName }}</div>
            <div class="tag-group-main">
              <b-button
                prefix-icon="plus"
                @click="addTag(item)"
                class="add-tag-btn"
                ghost="default"
                type="default"
                btn-content="添加"/>
              <a-tag
                v-for="(tag,index) in item.tagList"
                class="tag-item"
                :color="tag.select?'blue':''"
                :key="index"
                @click="batchAddTag(tag)">{{ tag.name }}
              </a-tag>
            </div>
          </div>
        </div>
      </div>
      <div class="d-jcs-aic mt-30">
        <a-button type="link" icon="plus-circle" style="padding: 0" @click="addTag()">新建标签组</a-button>
        <div>
          <b-button
            ghost="default"
            type="default"
            @click="hideTagAdd"
            btnContent="取消">
            取消
          </b-button>
          <b-button
            type="primary"
            style="margin-left: 10px"
            @click="saveCustomerTag"
            btnContent="确定"/>
        </div>
      </div>
    </a-modal>
    <a-modal v-model="searchTag" title="企业标签" :footer="null" width="640px">
      <div class="tag-update-wrap">
        <div class="d-aic tag-group-content mt-10" v-for="item in TagGroupList" :key="item.groupId">
          <div class="tag-group-name">{{ item.groupName }}</div>
          <div class="tag-group-main">
            <a-tag
              v-for="(tag,index) in item.tagList"
              class="tag-item"
              :color="tag.select?'blue':''"
              :key="index"
              @click="batchAddTag(tag)">{{ tag.name }}
            </a-tag>
          </div>
        </div>
      </div>
      <div class="d-aic mt-30">
        <div>
          <b-button
            ghost="default"
            type="default"
            @click="hideTagSearch"
            btnContent="取消">
            取消
          </b-button>
          <b-button
            type="primary"
            style="margin-left: 10px"
            @click="saveTagSearch"
            btnContent="确定"/>
        </div>
      </div>
    </a-modal>
  </b-page>
</template>

<script>
  import { STable } from '@/components'
  import COMMON_API from '../../../../api/common'
  import API from '../../../../api/customer'
  import TAG_API from '../../../../api/tag'
  import BButton from '../../../components/b-button'
  import storage from 'store'
  import { ACCESS_TOKEN } from '../../../../store/mutation-types'
  import BDataTitle from '../../../components/b-data-title'

  export default {
    name: 'KhglPage',
    components: {
      BDataTitle,
      BButton,
      STable
    },
    data () {
      return {
        pagination: {
          total: 0,
          pageSize: 10 // 每页中显示10条数据
        },
        // 高级搜索 展开/关闭
        advanced: false,
        loading: false,
        // 查询参数
        queryParam: {
          showTag: null,
          tag: null,
          gender: null,
          staffUserId: null,
          sourceName: null,
          leaveStatus: null,
          startTime: null,
          endTime: null,
          addTimes: []
        },
        genderList: [{ label: '男', value: 1 }, { label: '女', value: 2 }, { label: '未知', value: 0 }],
        memberList: [],
        lossList: [{ label: '未流失', value: 0 }, { label: '被动删除', value: 1 }, {
          label: '主动删除',
          value: 2
        }],
        sourceList: [{ label: '裂变活动', value: '裂变活动' }, { label: '默认来源', value: '默认来源' }],
        // 表头
        columns: [
          {
            title: '客户名',
              width: '200px',
            scopedSlots: { customRender: 'nickname' }
          },
          {
            title: '性别',
            width: '80px',
            scopedSlots: { customRender: 'gender' }
          },
          {
            title: '所属成员',
              width: '200px',
            dataIndex: 'staffUserName'
          },
          {
            title: '标签',
            width: '200px',
            scopedSlots: { customRender: 'tag' }
          },
          {
            title: '添加时间',
              width: '100px',
            scopedSlots: { customRender: 'addTIme' }
          },
          {
            title: '添加渠道',
              width: '100px',
            dataIndex: 'sourceName'
          },
          {
              width: '100px',
            scopedSlots: { title: 'leaveStatusTitle', customRender: 'leaveStatus' }
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'externalUserId' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        dataList: [],
        selectedRowKeys: [],
        selectedRows: [],
        parameter: {
          pageNo: 1,
          pageSize: 10,
          totalCount: 0
        },
        url: null,
        updateTag: false,
        TagGroupList: [],
        exportLoading: false,
        searchTag: false
      }
    },
    computed: {
      qwUserId () {
        return this.$store.state.user.info.qwUserId
      }
    },
    watch: {
      'queryParam.showTag' () {
        if (!this.queryParam.showTag) {
          this.queryParam.tag = null
        }
      }
    },
    // watch: {
    //   '$route.path' () {
    //     this.record = ''
    //     this.currentComponet = 'List'
    //   }
    // },
    mounted () {
      this.getData()
      this.getUrl()
      this.getMemberList()
      this.getTagList()
      this.checkRunningSyncTask()
    },
    methods: {
      hideTagAdd () {
        this.updateTag = false
        this.initTagSelect()
      },
      hideTagSearch () {
        this.searchTag = false
        this.initTagSelect()
      },
      saveTagSearch () {
        const tagList = this.getSelectTag()
        if (tagList.length) {
          this.queryParam.tag = tagList.join(',')
          this.queryParam.showTag = tagList[0] + ',共' + tagList.length + '个标签'
        }
        this.searchTag = false
        this.initTagSelect()
      },
      checkRunningSyncTask () {
        API.checkRunningSyncTask({ qwUserId: this.qwUserId }).then(res => {
          if (this.exportLoading && !res.synchronizing) {
            this.$message.success(`导入完成`)
            this.exportLoading = false
            this.getData()
          }
          if (res.synchronizing) {
            setTimeout(() => {
              this.checkRunningSyncTask()
            }, res.remaining + 2000)
          }
        })
      },
      getTagList () {
        TAG_API.list({ qwUserId: this.qwUserId }).then(res => {
          this.TagGroupList = res
          if (!this.TagGroupList.length) {
            return
          }
          this.initTagSelect()
        })
      },
      initTagSelect () {
        this.TagGroupList.forEach(item => {
          item.tagList.forEach(tag => {
            this.$set(tag, 'select', false)
          })
        })
      },
      addTag (item = {
        groupId: null,
        groupName: '',
        tagList: [{ name: '' }]
      }) {
        this.$refs.tagModal.show(item)
      },
      /**
       * 弹窗保存完成,更新列表
       */
      saveTag () {
        this.getTagList()
      },
      getSelectTag () {
        const tagList = []
        this.TagGroupList.forEach(item => {
          item.tagList.forEach(tag => {
            if (tag.select) {
              tagList.push(tag.name)
            }
          })
        })
        return tagList
      },
      saveCustomerTag () {
        const customerIdList = []
        const tagList = this.getSelectTag()
        if (!tagList.length) {
          this.$message.warning(`请先选择标签`)
          return
        }
        this.selectedRows.forEach(item => {
          customerIdList.push(item.id)
        })
        API.makeTag({
          qwUserId: this.qwUserId,
          customerIds: customerIdList.join(','),
          tags: tagList.join(',')
        }).then(res => {
          this.updateTag = false
          this.getData()
          this.initTagSelect()
          this.$message.success(`操作成功`)
        })
      },
      batchAddTag (tag) {
        tag.select = !tag.select
      },
      /**
       *构建导出名单链接
       */
      getUrl () {
        const token = storage.get(ACCESS_TOKEN)
        this.url = 'qw/qwCustomer/import?qwUserId=' + this.qwUserId + '&access_token=' + token
      },
      resetQueryParam () {
        this.queryParam = Object.assign({}, {
          showTag: null,
          tag: null,
          gender: null,
          staffUserId: null,
          sourceName: null,
          leaveStatus: null,
          startTime: null,
          endTime: null,
          addTimes: []
        })
      },
      getData () {
        API.CustomerPage(Object.assign({
          current: this.parameter.pageNo,
          size: this.parameter.pageSize,
          qwUserId: this.qwUserId
        }, this.queryParam))
          .then(res => {
            res.records.forEach(item => {
              item.tagList = []
              if (item.tag) {
                item.tagList = item.tag.split(',')
              }
            })
            this.dataList = res.records
            this.parameter.pageNo = res.current
            this.parameter.pageSize = res.size
            this.parameter.totalCount = res.total
            this.pagination.total = res.total
            this.loading = true
          }).catch(() => {
          this.loading = true
        })
      },
      handleTableChange (pagination) {
        this.pagination.current = pagination.current
        this.pagination.pageSize = pagination.pageSize
        this.parameter.pageNo = pagination.current
        this.parameter.pageSize = pagination.pageSize
        this.getData()
      },
      updateKhgl () {
        if (this.exportLoading) {
          this.$message.warning(`正在导入，请等待。。。`)
          return
        }
        this.exportLoading = true
        API.updateData({ qwUserId: this.qwUserId }).then(res => {
          this.exportLoading = true
          this.$message.warning(`正在同步，请等待。。。`)
          setTimeout(() => {
            this.checkRunningSyncTask()
          }, 5000)
        })
      },
      batchTag () {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(`请先选择需要打标签的客户`)
          return
        }
        // 如果是单个用户需要把之前的标签默认选好
        if (this.selectedRowKeys.length === 1) {
          const first = this.selectedRows[0].tagList
          this.TagGroupList.forEach(item => {
            item.tagList.forEach(tag => {
              first.forEach(selectTag => {
                if (tag.name === selectTag) {
                  tag.select = true
                }
              })
            })
          })
        } else {
          this.TagGroupList.forEach(item => {
            item.tagList.forEach(tag => {
              tag.select = false
            })
          })
        }
        this.updateTag = true
      },
      gotoDetail (customerId) {
        this.$emit('onEdit', customerId)
      },
      getTime (time) {
        return time ? this.$Utils.getTimeFormat(time).substring(0, 16) : ''
      },
      getMemberList () {
        const params = {
          qwUserId: this.qwUserId,
          active: 0,
          size: 1000,
          current: 0
        }
        COMMON_API.qwMemberPage(params).then(res => {
          this.memberList = res.records
        })
      },
      /**
       * 性别选择器
       */
      genderChange (data) {
        this.queryParam.gender = data
      },
      lossChange (data) {
        this.queryParam.leaveStatus = data
      },
      /**
       * 成员选择器
       */
      memberChange (data) {
        this.queryParam.staffUserId = data
      },
      /**
       * 渠道选择器
       */
      channelChange (data) {
        this.queryParam.sourceName = data
      },
      /**
       * 时间选择器
       */
      timeChange (data) {
        this.queryParam.startTime = data[0]
        this.queryParam.endTime = data[1]
        this.queryParam.addTimes = []
        this.queryParam.addTimes.push(this.$Utils.getTimestamp(data[0]))
        this.queryParam.addTimes.push(this.$Utils.getTimestamp(data[1]))
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>

<style scoped lang="less">
  .khgl-page {
    .select-state {
      font-size: 14px;
      color: #101010;
    }

    .select-state-num {
      font-size: 14px;
      margin: 0 6px;
      color: #ff5f5f;
    }

    .select-state-icon {
      margin-left: 10px;
      font-size: 18px;
      color: #ff5f5f;

      &.active {
        animation: syncAnimal 1.5s forwards infinite;
      }
    }

    .nickname-diy {
      font-size: 14px;
      color: #9f9f9f;
    }

    .remark-name {
      font-size: 14px;
      line-height: 26px;
      color: rgba(0, 0, 0, .65);
    }

    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
    }

    .ml-10 {
      margin-left: 10px;
    }

    .tag-item-style {
      max-width: 100px;
      margin: 0 8px 4px 0;
      padding: 0 7px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      color: #f5222d;
      background: #fff1f0;
      border: 1px solid #ffa39e;
    }
  }

  .tag-item {
    height: 32px;
    line-height: 32px;
  }

  .add-tag-btn {
    height: 32px;
    margin-right: 20px;

    &.active {
      border: 1px solid #ff5f5f;
    }
  }

  .tag-group-name {
    min-width: 80px;
  }
</style>
